<?php
namespace app\h5api\controller;

use app\common\model\Notice as NoticeModel;
use app\common\model\Settings;
use app\common\model\Shops;
use app\common\model\Banner;
use app\common\service\Wechat;
use plug\SHttp;
use think\Exception;
use think\exception\HttpException;
use think\facade\Config;

class Main extends Base
{
	/**
	 * @route('h5/ShopList','get')
	 * 店铺列表
	 */
	public function ShopList()
	{
		$key = input('get.key') ? input('get.key') : 'add_time' ;
		if (!in_array($key,['add_time','sales_volume','distance'])){
			$this->result([],-1,'key error');
		}

		$sort = input('get.sort') ? input('get.sort') : 'desc' ;
		if (!in_array($sort,['asc','desc'])){
			$this->result([],-1,'sort error');
		}
		if($key == 'distance' && (empty($this->lon) || empty($this->lat))){
		    $this->result([],-1,'选择距离排序，经纬度不能为空');
        }
		$field =[
			'shop_id','shop_name','imagesurl','address','province','city','area',
            '(select count(order_id) from ddt_order where shop_id = s.shop_id and order_status = 4 and order_type = 4) as sales_volume'
		];
		$orderby = '';
        if(!empty($this->lon) && !empty($this->lat)){
            $field[] = "FLOOR((st_distance (point (lon, lat), point({$this->lon}, {$this->lat})) * 111195) +1) AS distance";
//            $orderby = "distance asc";
            if($key == 'distance'){
                $sort = 'asc';
            }
        }
        if($orderby){
            $orderby .= ",{$key} {$sort}";
        } else {
            $orderby = $key." ".$sort;
        }
//        var_dump($field);
//        var_dump($sort);
		$ShopsModel = new Shops();
		$list = $ShopsModel->get_list_page([
			'approved' => 1,
			'state' => 1,
			'shop_types' => '1,3',
			'shop_name' => input('get.shop_name'),
		],"{$orderby}",$field,$this->limit);

		$this->result($list,1);
	}

	/**
	 * @route('h5/BannerList','get')
	 * 轮播图列表
	 */
	public function BannerList()
	{
		$BannerModel = new Banner();
		$list = $BannerModel->get_list_page('title,pic_url',[
			'pos' => input('get.type',1)
		],$this->limit);

		$this->result($list,1);
	}

	/**
	 * @route('h5/Noticelist','get')
	 * 轮播图列表
	 */
	public function Noticelist()
	{
		$noticeModel = new NoticeModel();
		$list = $noticeModel->get_list_page('notice_id,notice_title',null,$this->limit,'notice_id desc');

		$this->result($list,1);
	}

    /**
     * @route('h5/MapRequest','post')
     * 地图请求
     */
    public function MapInfo()
    {
        $lon = input('post.lon');
        $lat = input('post.lat');
        if(empty($lon) || empty($lat)){
            $this->result([],-1,'缺乏上传参数');
        }
        $mapconfig = Config::pull('mapconfig');
        $location = $lat.','.$lon;
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location={$location}&key={$mapconfig['Key']}&get_poi=0";
        $return = SHttp::http_curl($url);
        $data = json_decode($return['str'],true);
//        var_dump($data);die;
        if($data['status'] !== 0){
            $this->result([],-1,$data['message']);
        }
        $this->result($data['result'],1,'返回成功');
    }

    /**
     * @route('h5/wxmenu','post')
     * 微信自定义菜单栏
     */
    public function WeiXinMenu()
    {
        $data = [
            "button" => [
                [
                    "type" => "view",
                    "name" => "部长端",
                    "url" => "http://bfyc.jiazhengdashi.com/manager/ministerLogin",
                ],
            ],
        ];
        try{
            Wechat::createmenu($data);
        }catch(HttpException $e){
            $this->result('',-1,$e->getMessage());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/testsendmessage','post')
     * 测试发送消息
     */
    public function TestSendMessage()
    {
        $config = config::pull('weixin');
        $applet_config = config::pull('weixin_applet');
        $touser = 'ogqEU6R7BqMAzop9m3GrqUhfvbOU';
        $applet_touser = 'oV2eU5HkwO2BDEnYeHOM48GBWMFU';
        $model = new Settings();
        $setting = $model->get_list(['setg'=>'push_message'])->toArray();
        $setting = array_column($setting,'value','key');
//        var_dump(array_column($setting,'value','key'));die;
        $is_wx = true;
        if($is_wx){
            $template_id = $setting['credit_to_account'];// 公众号模板id
//            var_dump($template_id);die;
//            积分到账模板
            $data = [
                'amount3' => [
                    "value" => 123.00,
                ],//消费金额
                'time6' => [
                    "value" => date('Y-m-d H:i',time()),
                ],// 消费时间
                'number8' => [
                    "value" => 2.00,
                ],//会员积分
                'character_string14' => [
                    "value" => 2022111257565251,
                ],//订单号
                'thing20' => [
                    "value" => '大酒楼',
                ],//商家名称
            ];
            try{
                Wechat::wxmessagepush($config,$touser,$template_id,'',$applet_config['AppID'],'',$data);
            }catch(Exception $e){
                $this->result('',-1,$e->getMessage());
            }
        } else {
            $template_id = $setting['integral_change'];// 小程序模板id
//            积分变动模板
            $data = [
                'time7' => [
                    "value" => date('Y-m-d H:i:s',time()),
                ],// 变动时间
                'thing8' => [
                    "value" => 2,
                ],//变动原因
                'thing10' => [
                    "value" => 2022111257565251,
                ],//兑换内容
                'number12' => [
                    "value" => 2.00,
                ],//扣减积分
                'number14' => [
                    "value" => 45.00,
                ],//可用积分
            ];
            try{
                Wechat::messagepush($applet_config,$applet_touser,$template_id,'',$data);
            }catch(Exception $e){
                $this->result('',-1,$e->getMessage());
            }
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/findwxerror','post')
     * 查询错误信息
     */
    public function FindWxError()
    {
        $config = config::pull('weixin');
        $applet_config = config::pull('weixin_applet');
        $rid = input('post.rid');
        try{
            $data = Wechat::checkerror($config,'',$rid);
        }catch(Exception $e){
            $this->result('',-1,$e->getMessage());
        }
        $this->result($data,1,'操作成功');
    }

    /**
     * @route('h5/uploadwximage','post')
     * 上传微信永久图片素材
     */
    public function UploadWxImage()
    {
        $file = request()->file('image');// 获取表单上传文件 例如上传了001.jpg
        $basicpath = config::pull('imagesetting')['basic_path'];
        // 移动到框架应用根目录/uploads/ 目录下
        $ext = pathinfo($file->getInfo('name'))['extension'];
        $mime = $file->getInfo('type');
//        var_dump($ext);
//        var_dump($mime);die;
        //这个是是关键
        $info = $file->move($basicpath.'wx_media');
////        var_dump($info);
//        $imageinfo = [
//            'filename' => $info->getpathName(),
//            'content-type' => $info->getinfo()['type'],
//            'filelength' => $info->getinfo()['size'],
//        ];
//        var_dump($info->getpathName());
//        $path = realpath($info->getpathName());
//        var_dump($path);
//        $path = "http://bfyc.jiazhengdashi.com/uploads/wx_media/20230808/ccfb91e02c0560df72f5876ad1688e24.jpg";
        $media = new \CURLFile(realpath($info->getpathName()),$info->getinfo()['type'],$info->getfileName());
//        $media = new \CURLFile(realpath($info->getPathname()), $info->getinfo()['type'], ".{$info->getExtension()}");
//        var_dump($media);die;
//        var_dump($imageinfo);die;
        try{
            $data = Wechat::upload_wx_perpetual_image($media);
        }catch(Exception $e){
            $this->result('',-1,$e->getMessage());
        }
        $this->result($data,1,'操作成功');
    }
}
